<?php

!defined('IN_TIPASK') && exit('Access Denied');

class base {

    var $ip;
    var $time;
    var $db;
    var $cache;
    var $user = array();
    var $setting = array();
    var $category = array();
    var $nav = array();
    var $usergroup = array();
    var $get = array();
    var $post = array();
    var $regular; //当前访问的规则，例如 category/view
    var $statusarray= array('all'=>'全部','0'=>'待审核','1'=>'待解决','2'=>'已解决','4'=>'悬赏','9'=>'已关闭');

    function base(& $get,& $post) {
        $this->time = time();
        $this->ip = getip();
        $this->get=& $get;
        $this->post=& $post;
        $this->init_db();
        $this->init_cache();
        $this->init_user();
        $this->update_status();
        $this->banned();
    }

    function init_db() {
        $this->db=new db(DB_HOST, DB_USER, DB_PW, DB_NAME , DB_CHARSET , DB_CONNECT);
    }

    /*一旦setting的缓存文件读取失败，则更新所有cache*/
    function init_cache() {
        global $setting,$category,$badword;
        $this->cache=new cache($this->db);
        $setting=$this->setting=$this->cache->load('setting');
        $category=$this->category=$this->cache->load('category');
        $badword=$this->cache->load('badword','find');
        $this->usergroup=$this->cache->load('usergroup','groupid');
        $this->nav=$this->cache->load('nav','id','displayorder');
    }

    /*从缓存中读取数据，如果失败，则自动去读取数据然后写入缓存*/
    function fromcache($cachename, $cachetime=3) {
        $cachedata=$this->cache->read($cachename , intval($this->setting['index_life'])*60); //首页数据缓存，时间为3秒
        if($cachedata) return $cachedata;
        switch($cachename) {
            case 'nosolvelist': //待解决问题，网友正在问
                $this->load('question');
                $cachedata=$_ENV['question']->list_by_cfield_cvalue_status('',0,1,0,$this->setting['list_indexnosolve']);
                break;
            case 'solvelist'://已解决问题
                $this->load('question');
                $cachedata=$_ENV['question']->list_by_cfield_cvalue_status('',0,2,0,$this->setting['list_indexnosolve']);
                break;
            case 'rewardlist'://悬赏的问题
                $this->load('question');
                $cachedata=$_ENV['question']->list_by_cfield_cvalue_status('',0,4,0,$this->setting['list_indexreward']);
                break;
            case 'weekuserlist'://达人飙升榜
                $this->load('user');
                $cachedata=$_ENV['user']->list_by_credit(1,$this->setting['list_indexweekscore']);
                break;
            case 'alluserlist'://总积分榜
                $this->load('user');
                $cachedata=$_ENV['user']->list_by_credit(0,$this->setting['list_indexallscore']);
                break;
            case 'categorylist'://首页左侧分类列表
                $this->load('category');
                $cachedata=$_ENV['category']->list_by_grade();
                break;
            case 'recommendlist'://精彩推荐问题
                $this->load('recommend');
                $cachedata=$_ENV['recommend']->get_list(0,$this->setting['list_indexcommend']);
                break;
            case 'notelist'://首页右侧公告列表
                $this->load('note');
                $cachedata=$_ENV['note']->get_list(0,$this->setting['list_indexnote']);
                break;
            case 'famouslist'://问答名人堂
                $this->load('famous');
                $cachedata=$_ENV['famous']->get_list();
                break;
            case 'statistics'://首页统计，包含已解决、待解决
                $this->load('question');
                $cachedata = array();
                $cachedata['solves'] = $this->db->fetch_total('question', 'status IN (2,6)');   //已解决问题数
                $cachedata['nosolves'] = $this->db->fetch_total('question', 'status=1'); //待解决问题数
                break;
        }
        $this->cache->write($cachename,$cachedata);
        return $cachedata;
    }


    function load($model, $base = NULL) {
        $base = $base ? $base : $this;
        if(empty($_ENV[$model])) {
            require TIPASK_ROOT."/model/$model.class.php";
            eval('$_ENV[$model] = new '.$model.'model($base);');
        }
        return $_ENV[$model];
    }

    function init_user() {
        @$sid=tcookie('sid');
        @$auth=tcookie('auth');
        $user=array();
        @list($uid,$password) = empty($auth) ? array(0,0) : taddslashes(explode("\t", strcode($auth,$this->setting['auth_key'], 'DECODE')), 1);
        if(!$sid) {
            $sid=random(6);
            tcookie('sid',$sid,31536000);
        }
        if($uid && $password) {
            $user=$this->db->fetch_first('select * from '.DB_TABLEPRE.'user where uid='.$uid);
			$tem=$this->db->fetch_first('select snum from dy_user where uid='.$uid);
			$user['snum']=$tem['snum'];
			$tem=$this->db->fetch_first('select phone from dy_user where uid='.$uid);
			$user['phone']=$tem['phone'];
			
            ($password!=$user['password'])	&& $user=array();
        }
        if(!$user) {
            $user['uid']=0;
            $user['groupid']=6;
        }else {
            $user['newmsg']= $this->db->fetch_total('message',' touid='.$uid.'  AND `new`=1 AND `status`!=3  AND `status`!=2');
        }
        $user['sid']=$sid;
        $user['ip']=$this->ip;
        $user['loginuser']=$user['username'];
        //用户头像初始化
        $user['uid'] && $user['avatar']=get_avatar_dir($user['uid']);
        $this->user=array_merge($user, $this->usergroup[$user['groupid']]);
    }


    /*更新用户积分*/
    function credit($uid,$credit1,$credit2=0,$operation='') {
        if(!$operation) $operation=$this->get[0].'/'.$this->get[1];
        $this->db->query("INSERT INTO ".DB_TABLEPRE."credit(uid,time,operation,credit1,credit2) VALUES ($uid,{$this->time},'$operation',$credit1,$credit2) ");
        $this->db->query("UPDATE ".DB_TABLEPRE."user SET credit2=credit2+$credit2,credit1=credit1+$credit1 WHERE uid=$uid ");
        if ( 2 == $this->user['grouptype'] ) {
            $currentcredit1=$this->user['credit1']+$credit1;
            $usergroup = $this->db->fetch_first("SELECT g.groupid FROM ".DB_TABLEPRE."usergroup g WHERE  g.`grouptype`=2  AND $currentcredit1 >= g.creditslower ORDER BY g.creditslower DESC LIMIT 0,1");
            //判断是否需要升级
            if (is_array($usergroup) && ($this->user['groupid']!=$usergroup['groupid']) ) {
                $groupid = $usergroup['groupid'];
                $this->db->query("UPDATE ".DB_TABLEPRE."user SET groupid=$groupid WHERE uid=$uid ");
            }
        }
    }


    /*权限检测*/
    function checkable($url) {
        $this->regular=$url;
        if(1==$this->user['groupid']) return true;
        $regulars = explode(',', 'user/login,user/logout,user/code,user/getpass,user/resetpass,index/help,js/view,'.$this->user['regulars']);
        return in_array($url,$regulars);
    }

    /*IP禁止*/
    function banned() {
        $ips=$this->cache->load('banned');
        $ips=(bool)$ips?$ips:array();
        $userip=explode(".",$this->ip);
        foreach($ips as $ip) {
            $bannedtime=$ip['expiration']+$ip['time']-$this->time;
            if( $bannedtime>0
                    &&($ip['expiration']&&$ip['ip1']=='*'||$ip['ip1']==$userip[0])
                    &&($ip['ip2']=='*'||$ip['ip2']==$userip[1])
                    &&($ip['ip3']=='*'||$ip['ip3']==$userip[2])
                    &&($ip['ip4']=='*'||$ip['ip4']==$userip[3])
            ) {
                exit('IP被禁止访问！');
            }
        }
    }

    /*	中转提示页面
		$ishtml=1 表示是跳转到静态网页
    */
    function message($message,$url = '') {
        $seotitle='操作提示';
        if(''==$url) {
            $redirect=DY_URL;
        }else if('BACK'==$url) {
            $redirect=$url;
        }else if('RETURN'==$url){
			$redirect="javascript:history.go(-2);";
		}
		else {
            $redirect=SITE_URL.$this->setting['seo_prefix'].$url.$this->setting['seo_suffix'];
            if($this->setting['static_on']) {
                $redirect=SITE_URL.$url;
            }
        }
        $tpldir=(0===strpos($this->get[0],'admin'))?'admin':$this->setting['tpl_dir'];
        include template('tip',$tpldir);
        exit;
    }


    /*更新问题状态
	目前问题的状态共5种：
	四种显示的状态： 0、未审核  1、待解决、 4、悬赏的
	二种终结状态： 9、 已关闭问题 2、已解决
	方法 update_status(),每次读取10条中间状态的问题进行分析
    */
    function update_status() {
        $timenow=$this->time;
        $query = $this->db->query("SELECT * FROM `".DB_TABLEPRE."question` where  endtime<$timenow and status IN (1,4) ORDER BY endtime DESC LIMIT 0 ,10");
        while($question = $this->db->fetch_array($query)) {
            $this->db->query("UPDATE `".DB_TABLEPRE."question` set status=9  WHERE `id` =".$question['id']);
            $this->send($question['authorid'],$question['id'],2);
        }
    }

    /*发送通知
	一、操作导致状态改变
		A、当问题被人回答，系统会自动给问题提出者发送通知
		B、当问题被采纳为答案，回答者会收到消息

	二、时间导致状态改变
		A、问题变为关闭状态，给提问者发通知
		
	三、$type说明:
		0:问题有新回答
		1:回答被采纳
		2:问题超时自动关闭
    */
    function send($uid, $qid ,$type) {
        $question =  $this->db->fetch_first("SELECT * FROM ".DB_TABLEPRE."question WHERE id='$qid'");
        $msgtpl = unserialize($this->setting['msgtpl']);
        //消息模板
        $message = array();
        foreach ($msgtpl[$type] as $msg=>$val) {
            $message[$msg]=str_replace('title',$question['title'],$val);
            $message[$msg]=str_replace('description',$question['description'],$message[$msg]);
            $message[$msg]=str_replace('site_name',$this->setting['site_name'],$message[$msg]);
        }

        $message['content'] .='<br /> <a href="'.SITE_URL.$this->setting['seo_prefix'].'question/view/'.$qid.$this->setting['seo_suffix'].'">点击查看问题</a>';
        $time=$this->time;
        $msgfrom=$this->setting['site_name'].'管理员';
        $touser = $this->db->fetch_first("SELECT * FROM ".DB_TABLEPRE."user WHERE uid=".$uid);
        //1,3,5,7 允许站内消息
        if( (1 & $touser['isnotify']) && $this->setting['notify_message']) {
            $this->db->query('INSERT INTO '.DB_TABLEPRE."message  SET `from`='".$msgfrom ."' , `fromuid`=0 , `touid`=$uid  , `subject`='".$message['title']."' , `time`=" . $time . " , `content`='".$message['content'] ."'");
        }
        //2,3,6,7 允许发邮件
        if( (2 & $touser['isnotify']) && $this->setting['notify_mail']) {
            sendmail($touser, $message['title'], $message['content']);
        }
        //4,5,6,7 允许发手机短信
    }

    /*生成一个问题的静态页面*/
    function write_question($question) {
        global $setting,$db;
        include_once TIPASK_ROOT.'/control/question.php';
        $this->get[2]=$question['id'];
        $control = new questioncontrol($this->get,$this->post);
        ob_start();
        $control->onview();
        $html=ob_get_contents();
        ob_end_clean();

        $staticurl=getstaticurl($question);
        if($question['url'] && file_exists($question['url'])) {
            unlink($question['url']);
        }
        $this->db->query("UPDATE `".DB_TABLEPRE."question`  SET url='$staticurl'  WHERE id =".$question['id']);
        forcemkdir(dirname($staticurl));
        writetofile($staticurl,$html);
        return $staticurl;
    }


    /*检查验证码*/
    function checkcode() {
        $this->load('user');
        if(strtolower(trim($this->post['code'])) != $_ENV['user']->get_code()) {
            $this->message("验证码错误!",'BACK');
        }
    }


}


?>
